package graphicalInterface;

import grafics.BitmapRead;
import grafics.Library;

import java.io.*;
import java.sql.Connection;

import lexicalAnalysis.LexicalException;
import main.Analysis;
import main.Simulator;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.custom.StyledText;

import dataBaseInteraction.DataProcessing;

import sintacticAnalysis.SintaxErrorException;

/**
 * editorul de text ce suporta operatiile:
 *  new, open, save, copy, cut, paste, compile, play, quit
 *
 */
public class TextEditor {
	
	Shell shell2 = new Shell(HomeInterface.display);
	StyledText styledText;
	boolean unsaved;
	File file;
	String lastDirectory;
	StyledText textErori;

	public TextEditor() {
		
		shell2.setLayout(new GridLayout());
		ToolBar toolBar = new ToolBar(shell2, SWT.FLAT | SWT.RIGHT);
		ToolItem item1 = new ToolItem(toolBar, SWT.PUSH);
		
		/**
		 * Toolbar New
		 */
		item1.setText("New");
		item1.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (saveChanges()) {
					file = null;
					styledText.setText("");
				}
			}
		});
		
		/**
		 * Toolbar Open
		 */
		ToolItem item2 = new ToolItem(toolBar, SWT.PUSH);
		item2.setText("Open");
		item2.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				loadText();
			}
		});
		
		/**
		 * Toolbar Save
		 */
		ToolItem item3 = new ToolItem(toolBar, SWT.PUSH);
		item3.setText("Save");
		item3.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				saveText();
			}
		});
		
		/**
		 * Toolbar Copy
		 */
		ToolItem item4 = new ToolItem(toolBar, SWT.PUSH);
		item4.setText("Copy");
		item4.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				styledText.copy();
			}
		});
		
		/**
		 * Toolbar Cut
		 */
		ToolItem item5 = new ToolItem(toolBar, SWT.PUSH);
		item5.setText("Cut");
		item5.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				styledText.cut();
			}
		});
		
		/**
		 * Toolbar Paste
		 */
		ToolItem item6 = new ToolItem(toolBar, SWT.PUSH);
		item6.setText("Paste");
		item6.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				styledText.paste();
			}
		});
		
		/**
		 * Toolbar Compile
		 */
		ToolItem item8 = new ToolItem(toolBar, SWT.PUSH);
		item8.setText("Compile");
		item8.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event event) {
				// TODO Auto-generated method stub
				Analysis a;
				try {
					
					textErori.setText("");
					BufferedWriter bw=new BufferedWriter(new
					FileWriter("scenariu.txt"));
					bw.write(styledText.getText()); bw.close();
					a = new Analysis();	
					a.verify();
					BufferedReader br = new BufferedReader(new FileReader(
							"errorlog.txt"));
					String saux;
					if ((saux=br.readLine()) != null) {
						textErori.append(saux);
						textErori.append("\n");
						while ((saux=br.readLine()) != null)
						{
							textErori.append(saux);
							textErori.append("\n");
						}
					} 
					else
					{
						textErori.setText("Scenariul este corect");
					}
					br.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (LexicalException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SintaxErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		});
		
		/**
		 * Toolbar Play
		 */
		ToolItem item9 = new ToolItem(toolBar, SWT.PUSH);
		item9.setText("Play");
		item9.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event event) {
				// TODO Auto-generated method stub
				Analysis a;
				Simulator s;
				try {
					
					textErori.setText("");
					BufferedWriter bw=new BufferedWriter(new
					FileWriter("scenariu.txt"));
					bw.write(styledText.getText()); bw.close();
					a = new Analysis();	
					a.verify();
					BufferedReader br = new BufferedReader(new FileReader(
							"errorlog.txt"));
					String saux;
					if ((saux=br.readLine()) != null) {
						textErori.append(saux);
						textErori.append("\n");
						while ((saux=br.readLine()) != null)
						{
							textErori.append(saux);
							textErori.append("\n");
						}
					
					} else {
						HomeInterface gui = new HomeInterface(shell2);
						s = new Simulator();
						s.startSimulator();
						gui.run();
						
						// s.stopSimulator();
						gui.stopInterface();
					}
					br.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (LexicalException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SintaxErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		ToolItem item11 = new ToolItem(toolBar, SWT.PUSH);
		item11.setText("Grafice");
		item11.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event event) {
				// TODO Auto-generated method stub
				Library.CreateLibrary();
				String path1,path2,path3,path4,path5,path6;
				Connection dbConnection=DataProcessing.connectToDB(DataProcessing.userName, DataProcessing.password, DataProcessing.url);
				path1=BitmapRead.GeneratePlot(dbConnection, "senzor temperatura","senzor temperatura");
				path2=BitmapRead.GeneratePlot(dbConnection, "senzor gaz","senzor gaz");
				path3=BitmapRead.GeneratePlot(dbConnection, "senzor curent","senzor curent");
				path4=BitmapRead.GeneratePlot(dbConnection, "senzor apa baie 1","senzor apa baie 2");
				path5=BitmapRead.GeneratePlot(dbConnection, "senzor apa baie 2","senzor apa baie 1");
				path6=BitmapRead.GeneratePlot(dbConnection, "senzor apa bucatarie","senzor apa bucatarie");
				System.out.println(path1);
				System.out.println(path2);
				System.out.println(path3);
				System.out.println(path4);
				System.out.println(path5);
				System.out.println(path6);
			}});
		/**
		 * Toolbar Exit
		 */
		ToolItem item7 = new ToolItem(toolBar, SWT.PUSH);
		item7.setText("Exit");
		item7.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (saveChanges())
					shell2.dispose();
			}
		});
		toolBar.pack();
		/**
		 * editorul de text
		 */
		styledText = new StyledText(shell2, SWT.MULTI | SWT.WRAP | SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL);
		styledText.setLayoutData(new GridData(GridData.FILL_BOTH));
		Font font = new Font(shell2.getDisplay(), "Book Antiqua", 12,
				SWT.NORMAL);
		styledText.setFont(font);
		styledText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				unsaved = true;
			}
		});
		/**
		 * text-area pentru erori
		 */
		textErori=new StyledText(shell2,SWT.MULTI | SWT.WRAP | SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL );
		textErori.setLayoutData(new GridData(GridData.FILL_BOTH));
		textErori.setFont(font);
		textErori.setEditable(false);
		textErori.setBackground(HomeInterface.display.getSystemColor(SWT.COLOR_GRAY));
		shell2.setText("Editor");
		shell2.setSize(800, 500);
		shell2.open();
		while (!shell2.isDisposed()) {
			if (!HomeInterface.display.readAndDispatch()) {
				HomeInterface.display.sleep();
			}
		}
		HomeInterface.display.dispose();
	}

	/**
	 * salveaza modificarile facute
	 */
	boolean saveChanges() {
		if (!unsaved)
			return true;
		MessageBox box = new MessageBox(shell2, SWT.ICON_WARNING | SWT.YES
				| SWT.NO | SWT.CANCEL);
		box.setMessage("save changes? ");
		box.setText("Editor");
		int condition = box.open();
		if (condition == SWT.YES) {
			return saveText();
		} else if (condition == SWT.NO) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * incarca un fisier
	 */
	boolean loadText() {
		FileDialog dialog = new FileDialog(shell2, SWT.OPEN);
		if (lastDirectory != null)
			dialog.setFilterPath(lastDirectory);

		String selectedFile = dialog.open();
		if (selectedFile == null) {
			System.out.println("File is not opened");
			return false;
		}
		file = new File(selectedFile);
		lastDirectory = file.getParent();

		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			StringBuffer buffer = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
				buffer.append("\r\n");
			}
			styledText.setText(buffer.toString());
			return true;
		} catch (IOException e) {
		}
		return false;
	}

	/**
	 * salveaza textul
	 */
	boolean saveText() {
		if (file == null) {
			FileDialog fileDialog = new FileDialog(shell2, SWT.SAVE);
			if (lastDirectory != null)
				fileDialog.setFilterPath(lastDirectory);

			String selectedFile = fileDialog.open();
			if (selectedFile == null) {
				System.out.println("File is not saved");
				return false;
			}
			file = new File(selectedFile);
			lastDirectory = file.getParent();
		}
		try {
			FileWriter writer = new FileWriter(file);
			writer.write(styledText.getText());
			writer.close();
			unsaved = false;
			return true;
		} catch (IOException e) {
		}
		return false;
	}

	/**
	 * main
	 */
	public static void main(String args[]) {
		new TextEditor();
	}
}